package com.cloudcross.ssp.web.schedule;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.service.IAdGroupService;
import com.cloudcross.ssp.service.IAdgroupZoneService;
import com.cloudcross.ssp.service.IOrderService;
import com.cloudcross.ssp.service.impl.AdGroupService;

@Component("syncOffLine")
public class SyncOffLineScheduler {
    private Logger        logger           = LogManager.getLogger(getClass());
    
    private List<Integer>  onlinePcAds     = new ArrayList<Integer>();
    
    private List<Integer>  onlineAppAds    = new ArrayList<Integer>();
    
    private List<Integer> offLinePcAds     = new ArrayList<Integer>();
    
    private List<Integer> offLineAppAds    = new ArrayList<Integer>();
    
    @Autowired
    private IAdgroupZoneService adgroupZoneService;
    @Autowired
    private Config  config;
    @Autowired
    private IAdGroupService adgroupService;
    @Autowired
    private IOrderService orderService;
    
    private void clearData(){
        onlinePcAds.clear();
        onlineAppAds.clear();
        offLinePcAds.clear();
        offLineAppAds.clear();
    }
    
    
    private void initData(){
        onlinePcAds =  adgroupZoneService.onlinePcAds();
        offLinePcAds = adgroupZoneService.offLinePcAds();
        onlineAppAds = adgroupZoneService.onlineAppAds();
        offLineAppAds = adgroupZoneService.offLineAppAds();
    }
    
    private void offLineAds() {
        String manageDomain = config.getManageDomain();
        String mobileDomain = config.getAppDomain();
        offLinePcAds.removeAll(onlinePcAds);
        if (offLinePcAds.size() > 0) {
            for (Integer adsObj : offLinePcAds) {
                AdGroupService.noticeDirectOrder(manageDomain + "media/updateDirectOrder.do?adid=" + adsObj + "&state=0");
            }
        }
        offLineAppAds.removeAll(onlineAppAds);
        if (offLineAppAds.size() > 0) {
            for (Integer adsObj : offLineAppAds) {
                AdGroupService.noticeDirectOrder(
                        mobileDomain + "direct/updateDirectOrder.do?token=U2FsdGVkX18FaI4Z08yvcLB9WHQPTXbL0EnLZ4bCIo&adid=" + adsObj + "&status=0");
            }
        }
    }
    
    private void offlineOrderAndGroup(){
    	orderService.offLineOrder();
    	logger.info("off line order successful");
    	adgroupService.offLineAdgroup();
    	logger.info("off line adgroup successful");
    }
    
    public void runTask(){
        logger.info("off line ads running....");
        clearData();
        initData();
        offLineAds();
        offlineOrderAndGroup();
    }
}
